<script setup lang="ts">
import type { TreeInstance } from 'element-plus'
import type { SysDict } from '@/apis/system/sysDictApi'
import { Check, Close } from '@element-plus/icons-vue'
import { storeToRefs } from 'pinia'
import { computed, onMounted, ref, watch } from 'vue'
import { useDictStore } from '@/stores/dictStore'

const { appType, module } = defineProps<{ appType: string, module: string }>()

const appApis = ref<SysDict[]>()
const selectedApis = defineModel<string[]>()
const selectedModule = ref<string>()
const moduleTreeRef = ref<TreeInstance>()

const firstModule = computed(() => module.split('.')[0])

function remove(index: number) {
  if (selectedApis.value) {
    selectedApis.value?.splice(index, 1)
  }
}

const dialogVisible = ref(false)
const dictStore = useDictStore()
const { dictMap } = storeToRefs(dictStore)

async function onOpenDialog() {
  await dictStore.loadDict('MODULE')
  await loadApi()
  selectedModule.value = module
  moduleTreeRef.value?.setCurrentKey(module)
}

async function loadApi() {
  await dictStore.loadDict(`MODULE_API_${firstModule.value.toUpperCase()}_${appType}`)
  appApis.value = dictMap.value[`MODULE_API_${firstModule.value.toUpperCase()}_${appType}`]
}

onMounted(loadApi)

watch(() => firstModule.value, async () => {
  await loadApi()
  selectedApis.value = []
})

function clickModule(data: SysDict) {
  selectedModule.value = data.dictCode
}

function selectResource(apiKey: string) {
  if (selectedApis.value?.includes(apiKey)) {
    selectedApis.value = selectedApis.value.filter(i => i !== apiKey)
  }
  else {
    if (selectedApis.value === undefined) {
      selectedApis.value = [apiKey]
    }
    else {
      selectedApis.value.push(apiKey)
    }
  }
}

const selectedAppApis = computed(() => {
  return appApis.value?.filter(api => selectedApis.value?.includes(api.dictCode!))
})

const selectedModuleApis = computed(() => {
  if (selectedModule.value) {
    return appApis.value?.filter(api => api.customData?.moduleName?.startsWith(selectedModule.value!))
  }
  else {
    return appApis.value
  }
})
</script>

<template>
  <el-button type="primary" @click="dialogVisible = true">
    添加
  </el-button>

  <div class="w-full">
    <div
      v-for="(item, index) in selectedAppApis" :key="index"
      class="resource-item hover-bg-active hover-text-active"
    >
      <div>
        <span class="text-xs font-bold">   {{ item.dictName }} </span>
        <span class="ml-4 text-xs"> {{ item.dictCode }}</span>
      </div>

      <el-icon @click="remove(index)">
        <Close />
      </el-icon>
    </div>
  </div>

  <el-dialog
    v-model="dialogVisible"
    title="选择应用资源"
    width="800"
    node-key="dictCode"
    @open="onOpenDialog"
  >
    <div class="h-md flex flex-row justify-between gap-1">
      <div style="min-width: 150px;" class="overflow-auto border-1 rounded border-solid">
        <el-tree
          ref="moduleTreeRef"
          default-expand-all
          :data="dictMap.MODULE.filter(d => d.dictCode === firstModule)"
          :props="{ label: 'dictName' }"
          node-key="dictCode"
          highlight-current
          @node-click="clickModule"
        />
      </div>
      <div class="flex-1 overflow-auto border-1 rounded border-solid p-2 pr-4">
        <div
          v-for="(item, index) in selectedModuleApis" :key="index"
          :class="`resource-item ${selectedApis?.includes(item.dictCode!) ? 'resource-item-active' : ''}`"
          @click="selectResource(item.dictCode!)"
        >
          <div>
            <span class="text-xs font-bold">  {{ item.dictName }} </span>
            <span class="ml-4 text-xs"> {{ item.dictCode }}</span>
          </div>

          <el-icon>
            <Check v-if="selectedApis?.includes(item.dictCode!)" />
          </el-icon>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<style scoped>
.resource-item {
  --at-apply: my-1 flex flex-row cursor-pointer items-center justify-between rounded bg-secondary p-1;
}
.resource-item-active {
  --at-apply: bg-active text-active;
}
</style>
